package ru.urfc.portal.services;

import java.io.StringWriter;
import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.urfc.portal.model.documents.Document;
import ru.urfc.portal.model.documents.DocumentState;
import ru.urfc.portal.operations.DocumentContentService;

@MessageDriven(mappedName = "dmsQueue")
public class DmsMdb implements MessageListener {

	public boolean DummyDebug = false;
	public boolean Debug = false;
	public boolean HtmlDebug = false;
	public boolean DmsDebug = false;

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@PersistenceContext(name = "sys", unitName = "sys")
	public EntityManager sys;

	/** Context for the MDB. */
	// @Resource
	// private MessageDrivenContext mdbContext;

	public static class DocData {
		public String regNum; // now docId
		public Calendar dateOut; // now docId

		public String folder;
		public String category;
		public String title;
		public String html;
		public String primaryFilename;
		public String[] secondaryFilenames;

	}

	@EJB
	DocumentContentService documentContentService;
	
	public DocData getDocDataById(EntityManager sys, Document doc,
			boolean useTestHtml) {
		Long docId = doc.getId();
		DocData dd = new DocData();
		dd.regNum = docId.toString();
		dd.title = docId.toString();
		StringWriter sw = new StringWriter();
		if (useTestHtml) {
			DmsTest.TestHtmlContent(docId, sw);
		} else {
			documentContentService.htmlContent(doc, sw);
		}
		dd.html = sw.toString();
		dd.dateOut = Calendar.getInstance();
		dd.dateOut.setTime(doc.issueDate);

		if (DmsDebug) {
			dd.folder = DmsManager.DEFAULT_FOLDER_UUID;
			dd.category = DmsManager.DEFAULT_CATEGORY_UUID;
		} else {
			dd.folder = doc.getClient().getBranch().folderUuid; // DmsManager.DEFAULT_FOLDER_UUID
			dd.category = DmsCategory.getCategoryUuid(sys, doc); // DmsManager.DEFAULT_CATEGORY_UUID;
		}
		dd.primaryFilename = null; // TODO
		dd.secondaryFilenames = new String[] {}; // TODO
		return dd;
	}

	public Document getDoc(Long docId) {
//		Document doc = (Document) sys.createQuery(
//				"SELECT d FROM Document d WHERE d.id=:id").setParameter(
//				"id", docId).getSingleResult();
		Document doc = sys.find(Document.class, docId);
		return doc;

	}

	public void addTestDoc(EntityManager sys, Document doc) {
		Long docId = doc.getId();
		DmsTestEntity dte = new DmsTestEntity();
		dte.lc = "На рассмотрении";
		dte.incomingNumber = docId.toString();
		dte.incomingDate = new Date();
		sys.persist(dte);
		// dte =
		// (DmsTestEntity)sys.createQuery("SELECT d FROM DmsTestEntity d WHERE d.regnum =:regnum")
		// .setParameter("regnum", docId.toString()).getSingleResult();
		doc.lc = dte.lc;
		doc.dms = dte.getId().toString();
	}

	public void addDmsDoc(EntityManager sys, Document doc) {
		DmsManager dm = new DmsManager();
		DocData dd = getDocDataById(sys, doc, HtmlDebug);
		if (dm.tryAddDoc(dd.title, dd.regNum, dd.dateOut, dd.html,
				dd.primaryFilename, dd.secondaryFilenames, dd.folder,
				dd.category)) {
			doc.lc = dm.lc;
			setDocState(sys, doc, dm.lc);
			doc.incomingNumber = dm.incomingNumber;
			doc.incomingDate = dm.incomingDate;
			doc.dms = dm.dms;
			sys.persist(doc);
			logger.info("Adding of doc " + doc.getId() + " succeded");
		} else {
			logger.info("Adding of doc " + doc.getId() + " failed");
		}
	}

	public void addDoc(EntityManager sys, Document doc) {
		if (DummyDebug) {
			addDummyDoc(sys, doc);
		} else if (Debug) {
			addTestDoc(sys, doc);
		} else {
			addDmsDoc(sys, doc);
		}
	}

	public static DocumentState getInProgressState (EntityManager sys) {
		String sql = "select s from DocumentState s where s.code = :code";
		Query query = sys.createQuery(sql).setParameter("code", ru.urfc.portal.ui.client.model.catalogs.DocumentState.IN_PROGRESS.getCode());
		return (DocumentState) query.getSingleResult();
//		return sys.find(DocumentState.class, ru.urfc.portal.ui.client.model.catalogs.DocumentState.IN_PROGRESS.getCode());

		//		return new DocumentState(
//		 ru.urfc.portal.ui.client.model.catalogs.DocumentState.IN_PROGRESS.getCode(),
//		 ru.urfc.portal.ui.client.model.catalogs.DocumentState.IN_PROGRESS.getText());
	}
	public static DocumentState getSatisfiedState (EntityManager sys) {
		String sql = "select s from DocumentState s where s.code = :code";
		Query query = sys.createQuery(sql).setParameter("code", ru.urfc.portal.ui.client.model.catalogs.DocumentState.SATISFIED.getCode());
		return (DocumentState) query.getSingleResult();

//		return sys.find(DocumentState.class, ru.urfc.portal.ui.client.model.catalogs.DocumentState.SATISFIED.getCode());

//		return new DocumentState(
//		 ru.urfc.portal.ui.client.model.catalogs.DocumentState.SATISFIED.getCode(),
//		 ru.urfc.portal.ui.client.model.catalogs.DocumentState.SATISFIED.getText());
	}
	public static void setDocState(EntityManager sys, Document doc, String lc) {
		if (lc.equalsIgnoreCase("На рассмотрении")) {
			doc.setState(getInProgressState(sys));
		} else {
			doc.setState(getSatisfiedState(sys));
		}
	}
	public void addDummyDoc(EntityManager sys, Document doc) {
		doc.setState(getInProgressState(sys));
		sys.persist(doc);
	}

	@Override
	public void onMessage(Message message) {
		if (message instanceof ObjectMessage) {
			try {
				Long docId = (Long) ((ObjectMessage) message).getObject();
				logger.info("docId : {}", docId);
				Document doc = getDoc(docId);
				addDoc(sys, doc);
				// Document doc =
				// (Document)sys.createQuery("SELECT d FROM Document d WHERE d.id=:cust_id")
				// .setParameter("id", docId).getSingleResult();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
}
